package cn.stylefeng.guns.modular.business.frequency.ordersub.controller;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.app.controller.dto.CreatePayOrderDTO;
import cn.stylefeng.guns.modular.business.frequency.finance.service.FinanceService;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderVO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.*;
import cn.stylefeng.guns.modular.business.frequency.ordersub.service.OrderSubService;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.EasyExcelUtil;
import cn.stylefeng.guns.sys.modular.role.RoleConstant;
import cn.stylefeng.guns.sys.modular.user.entity.EnterpriseUserMsg;
import cn.stylefeng.guns.sys.modular.user.mapper.EnterpriseUserMsgMapper;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 子订单 控制器
 *
 * @author: yujie
 * @date: 2023/05/09 17:16
 */

@Api(tags = "订单管理（V2）")
@RequestMapping("/api/v2/order")
@RestController
public class OrderSubController {

    @Resource
    private OrderSubService orderSubService;
    @Resource
    private FinanceService financeService;
    @Resource
    private FinanceDetailMapper financeDetailMapper;
    @Autowired
    private BusinessUtil businessUtil;




    @ApiOperation(value = "创建订单")
    @PostMapping
    public ResponseData createOrder(@RequestBody @Validated OrderVO orderVO) {
        StringBuilder errorMsg = new StringBuilder();
        System.out.println("60 ="+System.currentTimeMillis());
        if (!orderSubService.checkOrderCreate(orderVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        System.out.println("64 ="+System.currentTimeMillis());
        return orderSubService.createOrder(orderVO);
    }

    //@NoRepeatSubmit
    @ApiOperation(value = "修改订单")
    @PutMapping
    public ResponseData updateOrder(@RequestBody @Validated OrderVO orderVO) {
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkOrderUpdate(orderVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        return orderSubService.updateOrder(orderVO);
    }

    public static void main(String[] args) {
        System.out.println(21*350 +3*350+3*350+8*350+5*350+1500);
    }

    @ApiOperation(value = "订单分页列表")
    @GetMapping
    public ResponseData getOrderListPage( OrderDTO orderDTO) {
        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        // 数据权限处理
        //getDataAuthorityParam(orderDTO);
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setUserIdList(empByOrgList);
        return orderSubService.getOrderListPage( orderDTO);
    }

    @Autowired
    private EnterpriseUserMsgMapper enterpriseUserMsgMapper;

    @ApiOperation(value = "订单详情")
    @GetMapping("/{id}")
    public ResponseData getOrderDetail(@PathVariable Long id,
                                   @RequestParam(value = "scene", required = false, defaultValue = "1")
                                   @ApiParam(name = "scene", value = "使用场景 1.订单详情（默认） 2.提车 3.签收 4.送车 ") Integer scene,
                                   @RequestParam(value = "transportId", required = false) Long transportId) {
        PkgOrderSub orderSub = orderSubService.getOrderDetail(id, scene, transportId);
        EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectOne(new LambdaQueryWrapper<EnterpriseUserMsg>()
                .eq(EnterpriseUserMsg::getTenantId, orderSub.getTenantId()));
        if (enterpriseUserMsg != null) {
            orderSub.setIsOpen("1");
        } else {
            orderSub.setIsOpen("2");
        }
        return ResponseData.success(orderSub);
    }

    @ApiOperation(value = "订单详情(分享使用)")
    @GetMapping("/share/{id}")
    public ResponseData getShareOrderDetail(@PathVariable Long id,
                                       @RequestParam(value = "scene", required = false, defaultValue = "1")
                                       @ApiParam(name = "scene", value = "使用场景 1.订单详情（默认） 2.提车 3.签收 4.送车 ") Integer scene,
                                       @RequestParam(value = "transportId", required = false) Long transportId) {
        PkgOrderSub orderSub = orderSubService.getOrderDetail(id, scene, transportId);
        return ResponseData.success(orderSub);
    }

    @ApiOperation(value = "编辑订单详情")
    @GetMapping("/update/detail")
    public ResponseData getOrderVOByOrderIds(@RequestParam("ids") Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        OrderVO orderVO = orderSubService.getOrderVOByOrderIdList(idList);
        return ResponseData.andaSuccess(orderVO);
    }


    @ApiOperation(value = "子订单状态进度条")
    @GetMapping("/status/{id}")
    public ResponseData getSubOrderStatus(@PathVariable String id) {
        OrderProgressVO progress = orderSubService.getSubOrderStatus(id);
        return ResponseData.success(progress);
    }

    @ApiOperation(value = "子订单状态进度条")
    @GetMapping("/status/share/{id}")
    public ResponseData getShareSubOrderStatus(@PathVariable String id) {
        OrderProgressVO progress = orderSubService.getSubOrderStatus(id);
        return ResponseData.success(progress);
    }

    @ApiOperation(value = "订单修改记录详情列表")
    @GetMapping("/{id}/modify-record")
    public ResponseData getOrderModifyRecord(@PathVariable Long id) {
        List<OrderModifyDetail> list = orderSubService.getOrderModifyRecord(id);
        return ResponseData.success(list);
    }

    @ApiOperation(value = "批量获取订单信息")
    @GetMapping("/multi/infos")
    public ResponseData getOrderInfos(@RequestParam("orderIds") List<Long> orderIds) {
        List<PkgOrderSubBase> list = orderSubService.getOrderInfos(orderIds);
        return ResponseData.success(list);
    }


    @ApiOperation(value = "批量取消订单")
    @PostMapping("/cancel")
    public ResponseData multiCancel(@RequestBody String[] ids) {
        List<String> idList = Arrays.asList(ids);
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkMultiCancel(idList, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.multiCancel(idList);
        return ResponseData.success();
    }
    @PutMapping("/finance")
    @ApiOperation(value = "订单财务数据修改")
    public ResponseData orderFinanceUpdate(@RequestBody OrderSub orderSub) {
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkOrderFinanceUpdate(orderSub, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.orderFinanceUpdate(orderSub);
        financeService.changeFinanceStatus(orderSub.getId());
        return ResponseData.success();
    }

    @ApiOperation(value = "订单发运成本编辑")
    @PutMapping("/transport-cost")
    public ResponseData updateOrderTransportCost(@RequestBody PkgTransportLevelDetailSimple orderTransport) {
        if (orderTransport == null || orderTransport.getOrderId()==null ||
                orderTransport.getTransportSimple().getId()==null || orderTransport.getCost() == null) {
            return ResponseData.andaError("参数错误！");
        }
        FinanceDetail fd = financeDetailMapper.getByOrderIdAndRelationId(8, orderTransport.getOrderId(), orderTransport.getTransportSimple().getId());
        if (fd != null && orderTransport.getCost().compareTo(fd.getHasSettlement()) < 0) {
            return ResponseData.andaError("费用不可小于已经结算的金额");
        }
        orderSubService.updateOrderTransportCost(orderTransport);
        return ResponseData.success();
    }

    @ApiOperation(value = "订单导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, OrderDTO orderDTO) throws Exception {

        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        // 数据权限处理
        //getDataAuthorityParam(orderDTO);
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setUserIdList(empByOrgList);
        orderDTO.setTenantId(businessUtil.getTenantId());
        //用户登录
        if (businessUtil.getTenantId() == -1) {
            SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
            orderDTO.setConsigneePhone(sysLoginUser.getAccount());
        }
        //如果是网点人员，查询该网点人员所在网点的服务城市，以及自己创建订单的出发地
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        List<String> roleCodeList = sysUserService.getRoleCodeListByUserId(sysLoginUserId);
        if (roleCodeList.contains(RoleConstant.网点部角色)) {
            //查询该网点人员所在网点的服务城市，以及自己创建订单的出发地 的城市code
            orderSubService.setSiteCityCodeList(orderDTO, sysLoginUserId);
        }
        EasyExcelUtil.export2Web(response, "订单数据", "sheet1",
                OrderSubExport.class, orderSubService.getOrderExportList(orderDTO));
    }

    @Autowired
    private SysUserService sysUserService;



    @ApiOperation(value = "修改车架号")
    @PutMapping("/vin")
    public ResponseData updateVin(@RequestBody OrderSub orderSub) {
        if (orderSub == null || orderSub.getId()==null || StringUtils.isEmpty(orderSub.getVin())) {
            return ResponseData.andaError("参数错误");
        }
        orderSubService.updateVin(orderSub.getId(), orderSub.getVin());
        return ResponseData.success();
    }

}
